<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!-- 输入框，将内容发送到服务器 -->
    <input type="text">
    <!-- 按钮 -->
    <button>发送</button>
    <!-- 将获取到服务器的数据填写到div中1 -->
    <div></div>

    <div class="img">
        <label for="file"></label>
        <input type="file" name="" id="file">
    </div>

    <script>
        let fileElement = document.getElementById('file')
        fileElement.onchange = function( ){
            console.log(this.files[0])
            // console.log(URL.createObjectURL(this.files[0]))
            // console.log('---')
            var reader  = new FileReader();
            reader.readAsArrayBuffer(this.files[0])
            reader.onload = function(){
                // 获取到图片的base64
                console.log(reader.result)
            }
        }
        let input = document.querySelector('input')
        let button = document.querySelector('button')
        let div = document.querySelector('div')


        // 连接的服务器地址
        const socket = new WebSocket('ws://localhost:8081')
        // 添加连接成功事件
        socket.addEventListener('open', e =>{
            console.log('连接服务器成功!')
            div.innerHTML = '服务器连接成功'
        })
        
        button.addEventListener('click', ()=>{
            let value =  input.value 
            //主动发送信息给服务器的websocket
            socket.send(value)
        })
        // 接收服务器websocket的消息
        socket.addEventListener('message', e =>{
            let obj = JSON.parse(e.data)

            //将获取到的数据追加到最外层的div中
            let child = document.createElement('div')
            child.innerHTML = obj.msg
            child.style.color = obj.color
            div.appendChild(child)
        })
    </script>
</body>
</html>